<template>
  <div>
    <div class="search-box">
      <a-input @keydown.enter="search" v-model:value="book" class="search-input" placeholder="请输入书名"><template v-slot:prefix><BookOutlined /></template></a-input>
      <a-input @keydown.enter="search" v-if="$root.isAdmin" v-model:value="user" class="search-input" placeholder="请输入用户名"><template v-slot:prefix><UserOutlined /></template></a-input>
      <a-button type="primary" @click="search">搜索</a-button>
    </div>
    <a-table rowKey="id" :columns="columns" :data-source="data" :pagination="pagination" @change="handleTableChange">
      <template v-slot:type="{ text }">
        <span :style="{color:text==='0'?'green':'red'}">{{text==='0'?'归还':'借出'}}</span>
      </template>
      <template v-slot:action="{ text }">
        <a-button :disabled="text.type==='0'" type="primary" @click="updateRecord(text)">还书</a-button>
      </template>
    </a-table>
  </div>
</template>
<script>
const columns = [
  {
    title: '书名',
    dataIndex: 'book',
  },
  {
    title: '用户名',
    dataIndex: 'user',
  },
  {
    title: '状态',
    dataIndex: 'type',
    slots: { customRender: 'type' },
  },
  {
    title: '借书日期',
    dataIndex: 'createTime',
  },
  {
    title: '归还日期',
    dataIndex: 'updateTime',
  },
  {
    title: '操作',
    slots: { customRender: 'action' },
  },
];
export default {
  data() {
    return {
      book:'',
      user:'',
      data:[],
      columns,
      pagination:{
        current:1,
        pageSize: 10,
        total:0
      }
    };
  },
  methods:{
    handleTableChange(pagination){
      this.pagination.current = pagination.current
      this.search()
    },
    updateRecord(obj){
      this.$confirm({
        title: `确认归还《${obj.book}》吗？`,
        content: '归还后不可恢复',
        okText: '确定',
        cancelText: '取消',
        onOk:() => {
          this.$http.get('/updateRecord',{id:obj.id,bookId:obj.bookId}).then(_=>{
            this.$message.success(`归还 ${obj.book} 成功`)
            this.search()
          })
        },
      });
    },
    update(obj){
      this.$root.bookData = obj
      this.$router.push('/add')
    },
    search(){
      var obj = {
        current: this.pagination.current,
        pageSize: this.pagination.pageSize,
      }
      if(this.book){
        obj.book = this.book
      }
      if(this.user){
        obj.user = this.user
      }
      this.$http.get('/getRecord',obj).then(_=>{
        this.data = _.data
        this.pagination.total = _.total
      })
    }
  },
  mounted(){
    if(this.$route.params.book){
      this.book = this.$route.params.book
    }else if(this.$route.params.user){
      this.user = this.$route.params.user
    }
    if(localStorage.type!=='0'){
      this.user = localStorage.username
    }
    this.search()
  }
};
</script>
<style>
.book-img{
  width: 80px;
}
</style>